import os
import importlib
import inspect
from proxy_app.app import ParentApp

current_dir = os.path.dirname(__file__)

app_cache = {}  # app缓存


def load_app():  # 加载APP
    global app_cache
    app_cache = {}
    app_path = os.path.join(current_dir, "proxy_app", "app")
    load_app_from_path(app_path)



def get_app(app_name):  # 获取app
    global app_cache
    return app_cache.get(app_name) if app_cache.__contains__(app_name) else app_cache.get('parent-app')


def load_app_from_path(app_path):  # 加载APP
    # 遍历文件夹
    for file in os.listdir(app_path):
        if file.endswith('.py') and file != "__init__.py":
            # 构建模块路径
            module_name = f"proxy_app.app.{file[:-3]}"
            try:
                # 导入模块
                module = importlib.import_module(module_name)
                # 获取模块中的类定义
                classes = inspect.getmembers(module, inspect.isclass)
                # 遍历类定义
                for name, cls in classes:
                    # 检查是否是指定父类的真子类
                    if issubclass(cls, ParentApp.ParentApp) :
                        # 实例化子类
                        instance = cls()
                        app_cache[instance.get_app_name()] = instance
            except ModuleNotFoundError as e:
                print(f"模块 {module_name} 导入失败: {e}")
            except Exception as e:
                print(f"加载模块 {module_name} 时出错: {e}")


load_app()